//
//  UIImage-Extension.swift
//  Whiteboard
//
//  Created by point on 2018/1/4.
//  Copyright © 2018年 point. All rights reserved.
//

import Foundation
import Kingfisher

extension UIImage
{
    static func icon(from code: String ,color: UIColor, imageSize: CGSize) -> UIImage
    {
        let drawText = code
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = NSTextAlignment.center
        drawText.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height), withAttributes: [NSAttributedString.Key.font : UIFont(name:"iconfont", size: imageSize.width)!,NSAttributedString.Key.foregroundColor: color])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        guard image != nil else{
            return UIImage()
        }
        return image!
    }
    
    static func emptyImage(imageSize: CGSize) ->UIImage {
        return icon(from: kIcon_pic, color: kColorGray, imageSize: imageSize)
    }
    
    
    static func formatImageSize(size:CGSize) -> CGRect {
        let imgWidth:CGFloat = size.width
        let imgHeight:CGFloat = size.height
        var x:CGFloat = 0
        var y:CGFloat = 0
        var showWidth:CGFloat = 0
        var showHeight:CGFloat = 0
        
        //宽高都小于页面
        if imgWidth <= kScreenW && imgHeight <= kScreenH {
            x = (kScreenW - imgWidth) / 2
            y = (kScreenH - imgHeight) / 2
            showWidth = imgWidth
            showHeight = imgHeight
        }
        
        //宽高都大于页面
        if imgWidth >= kScreenW && imgHeight > kScreenH {
            print(imgWidth,imgHeight)
            
            print(imgWidth/imgHeight,kScreenW/kScreenH)
            
            if imgWidth/imgHeight >=  kScreenW/kScreenH { //显示宽屏
                x = 0
                showWidth = kScreenW
                showHeight = imgHeight * kScreenW  / imgWidth
                y = (kScreenH - showHeight) / 2
                print("计算好的z",showWidth,showHeight)
            }else { //显示窄的
                y = 0
                showHeight = kScreenH
                showWidth =  imgWidth * kScreenH / imgHeight
                x = (kScreenW - showWidth) / 2
                print("计算好的k",showWidth,showHeight)
            }
            
        }
        
        //宽大于页面  高小于页面
        if imgWidth >= kScreenW && imgHeight <=  kScreenH {
            showWidth = kScreenW
            x = 0
            showHeight = imgHeight * kScreenW / imgWidth
            y = (kScreenH - showHeight) / 2
        }
        
        //宽小于页面 高大于页面
        if imgWidth <= kScreenW && imgHeight >=  kScreenH {
            y = 0
            showHeight = kScreenH
            showWidth = imgWidth * kScreenH / imgHeight
            x = (kScreenW - showWidth) / 2
        }
        return CGRect(x: x, y: y, width: showWidth, height: showHeight)
    }
    
     func formatImageSizeTwo(size:CGSize) -> CGRect {
        var x:CGFloat = 0
        var y:CGFloat = 0
        var showHeight:CGFloat = 0
        var showWidth:CGFloat = 0
        
        if (size.width < size.height) {
            showWidth =  size.width * kScreenH / size.height
            y = 0
            x = (kScreenW - showWidth) * 0.5
            showHeight = kScreenH
            if (showWidth > kScreenW) { //如果显示的宽度 还大于屏幕的宽de
                x = 0
                showHeight =  kScreenW * showHeight / showWidth
                y = (kScreenH - showHeight) * 0.5
                showWidth = kScreenW
            }
        } else if (size.width > size.height) {
            x = 0
            showWidth = kScreenW
            showHeight = kScreenW * size.height /  size.width
            y = (kScreenH - showHeight) * 0.5
            
        }else {
            showWidth = kScreenW
            showHeight = kScreenW
            x = 0
            y = (kScreenH - kScreenW) * 0.5
        }
        return CGRect(x: x, y:y , width: showWidth, height: showHeight)
    }
    
    
    
    func rotate(aImage:UIImage) -> UIImage {
        // No-op if the orientation is already correct
        if aImage.imageOrientation == .up {
            return aImage
        }
        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
        var transform: CGAffineTransform = CGAffineTransform.identity
        switch aImage.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: aImage.size.width, y: aImage.size.height)
            transform = transform.rotated(by: CGFloat(M_PI))
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: aImage.size.width, y: 0)
            transform = transform.rotated(by: CGFloat(M_PI_2))
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: aImage.size.height)
            transform = transform.rotated(by: CGFloat(-M_PI_2))
        default:
            break
        }
        
        switch aImage.imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: aImage.size.width, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: aImage.size.height, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        default:
            break
        }
        
        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        
        
        
        let ctx: CGContext = CGContext(data: nil, width: Int(aImage.size.width), height: Int(aImage.size.height), bitsPerComponent: aImage.cgImage!.bitsPerComponent, bytesPerRow: 0, space: aImage.cgImage!.colorSpace!, bitmapInfo: aImage.cgImage!.bitmapInfo.rawValue)!
        ctx.concatenate(transform)
        switch aImage.imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            // Grr...
            ctx.draw(aImage.cgImage!, in: CGRect(x: 0, y: 0, width: aImage.size.height, height: aImage.size.width))
        default:
            ctx.draw(aImage.cgImage!, in: CGRect(x: 0, y: 0, width: aImage.size.width, height: aImage.size.height))
        }
        
        // And now we just create a new UIImage from the drawing context
        let cgimg: CGImage = ctx.makeImage()!
        let img: UIImage = UIImage(cgImage: cgimg)
        return img
        
    }
    
    func square(aImage:UIImage) -> UIImage {
        
        let width = aImage.size.width
        let height = aImage.size.height
        
        if(width>height){
            let x = (width - height)/2
            let rect = CGRect(x: x, y: x, width: height, height: height)
            return getImageFromImage(oldImage: aImage, newImageRect: rect)
            
        }else if (height>width){
            let y = (height - width)/2
            let rect = CGRect(x: 0, y: y, width: width, height: width)
            return getImageFromImage(oldImage: aImage, newImageRect: rect)
        }else{
            return aImage;
        }
    }
    func getImageFromImage(oldImage:UIImage,newImageRect:CGRect) ->UIImage {
        let imageRef = oldImage.cgImage;
        let subImageRef = imageRef!.cropping(to: newImageRect);
        return UIImage(cgImage: subImageRef!)
    }
    
    func resizeImage(_ dimension: CGFloat, opaque: Bool, contentMode: UIView.ContentMode = .scaleAspectFit) -> UIImage {
        var width: CGFloat
        var height: CGFloat
        var newImage: UIImage
        
        let size = self.size
        let aspectRatio =  size.width/size.height
        
        switch contentMode {
        case .scaleAspectFit:
            if aspectRatio > 1 {                            // Landscape image
                width = dimension
                height = dimension / aspectRatio
            } else {                                        // Portrait image
                height = dimension
                width = dimension * aspectRatio
            }
            
        default:
            fatalError("UIIMage.resizeToFit(): FATAL: Unimplemented ContentMode")
        }
        
        if #available(iOS 10.0, *) {
            let renderFormat = UIGraphicsImageRendererFormat.default()
            renderFormat.opaque = opaque
            let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
            newImage = renderer.image {
                (context) in
                self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
            }
        } else {
            UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), opaque, 0)
            self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
            newImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        }
        
        return newImage
    }
    
    func resizeImage(_ newSize: CGSize) -> UIImage? {
        func isSameSize(_ newSize: CGSize) -> Bool {
            return size == newSize
        }
        
        func scaleImage(_ newSize: CGSize) -> UIImage? {
            func getScaledRect(_ newSize: CGSize) -> CGRect {
                let ratio   = max(newSize.width / size.width, newSize.height / size.height)
                let width   = size.width * ratio
                let height  = size.height * ratio
                return CGRect(x: 0, y: 0, width: width, height: height)
            }
            
            func _scaleImage(_ scaledRect: CGRect) -> UIImage? {
                UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0);
                draw(in: scaledRect)
                let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
                UIGraphicsEndImageContext()
                return image
            }
            return _scaleImage(getScaledRect(newSize))
        }
        
        return isSameSize(newSize) ? self : scaleImage(newSize)!
    }
}


